<template>
  <div class="tab-content-box" :style="'min-height:' + (mainContextHeight - 76) + 'px'">
    <table-box
      class="page-table"
      :data="fragmentAgentToMe.ProcessAgent.impl.dataList"
      @sort-change="fragmentAgentToMe.ProcessAgent.impl.onSortChange"
      @refresh="refreshFragmentAgentToMe(true)"
      :seq-config="{
        startIndex:
          (fragmentAgentToMe.ProcessAgent.impl.currentPage - 1) *
          fragmentAgentToMe.ProcessAgent.impl.pageSize,
      }"
    >
      <vxe-column title="序号" type="seq" width="60px" />
      <vxe-column title="委托人" field="delegateUserName" />
      <vxe-column title="委托范围" show-overflow="title">
        <template #default="{ row }">
          {{ formatDelegateScope(row.delegateScope) }}
        </template>
      </vxe-column>
      <vxe-column title="委托流程" show-overflow="title">
        <template #default="{ row }">
          {{ formatProcessDefinition(row.processDefinitionKeys) }}
        </template>
      </vxe-column>
      <vxe-column title="开始时间" field="startTime" />
      <vxe-column title="结束时间" field="endTime" />
      <vxe-column title="委托说明" field="memo" show-overflow="title" />
      <vxe-column title="确认状态">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row)" :size="layoutStore.defaultFormItemSize">
            {{ getStatusValue(row) }}
          </el-tag>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right" width="120px">
        <template #default="{ row }">
          <el-button
            @click="onConfirmClick(row, true)"
            type="primary"
            link
            :size="layoutStore.defaultFormItemSize"
            :disabled="
              row.flowDelegatedUser?.confirmStatus !== 0 || new Date() >= new Date(row.endTime)
            "
          >
            接受
          </el-button>
          <el-button
            @click="onConfirmClick(row, false)"
            type="danger"
            link
            :size="layoutStore.defaultFormItemSize"
            :disabled="
              row.flowDelegatedUser?.confirmStatus !== 0 || new Date() >= new Date(row.endTime)
            "
          >
            拒绝
          </el-button>
        </template>
      </vxe-column>
      <template v-slot:pagination>
        <el-row type="flex" justify="end" style="margin-top: 16px">
          <el-pagination
            :total="fragmentAgentToMe.ProcessAgent.impl.totalCount"
            :current-page="fragmentAgentToMe.ProcessAgent.impl.currentPage"
            :page-size="fragmentAgentToMe.ProcessAgent.impl.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="fragmentAgentToMe.ProcessAgent.impl.onCurrentPageChange"
            @size-change="fragmentAgentToMe.ProcessAgent.impl.onPageSizeChange"
          >
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script setup lang="ts">
import { inject, reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { TableOptions } from '@/common/types/pagination';
import { useTable } from '@/common/hooks/useTable';
import { TableData } from '@/common/types/table';
import { ANY_OBJECT } from '@/types/generic';
import { useLayoutStore } from '@/store';
import { FlowDelegateUserController, FlowEntryController } from '@/api/flow';
import { SysCommonBizController } from '@/api/system';

const layoutStore = useLayoutStore();
const mainContextHeight = inject('mainContextHeight', 200);

// 用户字典缓存
const userDict = ref<Record<string, ANY_OBJECT>>({});

// 加载用户字典数据
const loadUserDict = (userIds: string[]) => {
  if (!userIds.length) return Promise.resolve();

  const params = {
    widgetType: 'upms_user',
    fieldValues: userIds.join(','),
  };

  return SysCommonBizController.viewByIds(params, { showMask: false })
    .then(res => {
      const newDict = (res.data || []).reduce(
        (acc: Record<string, ANY_OBJECT>, user: ANY_OBJECT) => {
          acc[user.userId] = user;
          return acc;
        },
        {},
      );
      userDict.value = { ...userDict.value, ...newDict };
    })
    .catch(e => {
      console.warn(e);
    });
};

// 委托范围字典
const delegateScopeDict = {
  user: '用户',
  dept: '部门',
  post: '岗位',
  dept_post: '部门岗位',
  role: '角色',
};

// 流程定义缓存
const processDefinitionDict = ref<Record<string, string>>({});

const ConfirmStatus = {
  PENDING: 0,
  APPROVED: 1,
  REJECTED: 2,
};

// 加载流程定义列表
const loadProcessDefinitionDict = () => {
  FlowEntryController.listDictByKey({})
    .then(res => {
      const dict: Record<string, string> = {};
      const list = Array.isArray(res.data) ? res.data : res.data?.dataList || [];
      list.forEach((item: ANY_OBJECT) => {
        dict[item.id] = item.name;
      });
      processDefinitionDict.value = dict;
    })
    .catch(e => {
      console.warn(e);
    });
};

// 格式化委托范围
const formatDelegateScope = (scope: string) => {
  if (!scope) return '';
  const scopes = scope.split(',');
  // 检查是否包含所有可能的范围
  const allScopes = ['user', 'dept', 'post', 'dept_post', 'role'];
  const isAll = allScopes.every(s => scopes.includes(s));
  if (isAll) return '全部';
  return scopes.map(s => delegateScopeDict[s] || s).join(',');
};

// 格式化流程定义
const formatProcessDefinition = (keys: string) => {
  if (!keys) return '全部';
  return keys
    .split(',')
    .map(key => processDefinitionDict.value[key] || key)
    .join(',');
};

/**
 * 加载代理数据
 */
const loadProcessAgentData = (params: ANY_OBJECT): Promise<TableData<ANY_OBJECT>> => {
  return new Promise((resolve, reject) => {
    FlowDelegateUserController.listMyDelegated(params)
      .then(res => {
        // 获取所有委托人ID
        const userIds = res.data.dataList.reduce((acc: string[], item: ANY_OBJECT) => {
          if (item.createUserId && !userDict.value[item.createUserId]) {
            acc.push(item.createUserId);
          }
          return acc;
        }, []);

        // 如果有未缓存的用户ID，先加载用户信息
        const loadDictPromise = userIds.length ? loadUserDict(userIds) : Promise.resolve();

        loadDictPromise.then(() => {
          // 添加用户名称信息
          const dataList = res.data.dataList.map((item: ANY_OBJECT) => ({
            ...item,
            delegateUserName: userDict.value[item.createUserId]?.showName || item.createUserId,
          }));

          resolve({
            dataList,
            totalCount: res.data.totalCount,
          });
        });
      })
      .catch(reject);
  });
};

/**
 * 列表数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadProcessAgentVerify = () => {
  return true;
};

const tableOptions: TableOptions<ANY_OBJECT> = {
  loadTableData: loadProcessAgentData,
  verifyTableParameter: loadProcessAgentVerify,
  paged: true,
};

const fragmentAgentToMe = reactive({
  ProcessAgent: {
    impl: useTable(tableOptions),
  },
  isInit: false,
});

const refreshFragmentAgentToMe = (reloadData = false) => {
  if (reloadData) {
    fragmentAgentToMe.ProcessAgent.impl.refreshTable(true, 1);
  } else {
    fragmentAgentToMe.ProcessAgent.impl.refreshTable();
  }
  fragmentAgentToMe.isInit = true;
};

const onConfirmClick = (row: ANY_OBJECT, isApprove: boolean) => {
  const action = isApprove ? '接受' : '拒绝';
  ElMessageBox.confirm(`是否${action}该委托申请？`, '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const params = {
        delegateId: row.id,
        confirmStatus: isApprove ? ConfirmStatus.APPROVED : ConfirmStatus.REJECTED,
      };
      FlowDelegateUserController.updateDelegatedUserConfirm(params)
        .then(() => {
          ElMessage.success(`${action}成功`);
          fragmentAgentToMe.ProcessAgent.impl.refreshTable();
        })
        .catch(e => {
          console.warn(e);
        });
    })
    .catch(() => {
      // do nothing
    });
};

const formInit = () => {
  // 加载流程定义字典
  loadProcessDefinitionDict();
  // 初始化表格数据
  refreshFragmentAgentToMe(true);
};

onMounted(() => {
  formInit();
});

const getStatusType = (row: ANY_OBJECT) => {
  // 检查是否过期
  const now = new Date();
  const endTime = new Date(row.endTime);
  const isExpired = now > endTime;

  // 如果已过期且未确认，显示过期状态
  if (isExpired && row.flowDelegatedUser?.confirmStatus === 0) {
    return 'danger';
  }

  // 如果已确认，根据确认状态显示
  switch (row.flowDelegatedUser?.confirmStatus) {
    case 1:
      return 'success';
    case 2:
      return 'danger';
    default:
      return 'info';
  }
};

const getStatusValue = (row: ANY_OBJECT) => {
  // 检查是否过期
  const now = new Date();
  const endTime = new Date(row.endTime);
  const isExpired = now > endTime;

  // 如果已过期且未确认，显示过期状态
  if (isExpired && row.flowDelegatedUser?.confirmStatus === 0) {
    return '已过期';
  }

  // 如果已确认，根据确认状态显示
  switch (row.flowDelegatedUser?.confirmStatus) {
    case 1:
      return '已接受';
    case 2:
      return '已拒绝';
    default:
      return '待确认';
  }
};

defineExpose({
  refreshFragmentAgentToMe,
});
</script>

<style lang="scss" scoped>
:deep(.operator-box) {
  min-height: 32px;
}
</style>
